package controller.commands;

import controller.Constants;
import controller.StoreFactory;
import core.InPort;
import core.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import model.graphic.GraphicModel;
import model.graphic.locations.FlexibleRelativeLocation;
import model.graphic.locations.Location;
import model.graphic.objects.Attachment;
import model.graphic.objects.GInput;
import model.graphic.objects.GInputPort;
import model.graphic.objects.GNode;
import model.graphic.objects.GOutput;
import model.graphic.objects.Graphical;
import load.parent.Store;
import view.GUI.graphic.GraphicView;

/**
 *
 * @author Ben
 */
public class AddDefaultValuesCommand extends BasicCommand{
    private GraphicModel gmodel;
    private GNode gnode;
    private GraphicView gview;
    private Node node;

    public AddDefaultValuesCommand(GraphicModel gmodel, GNode gnode,Node node, GraphicView gview) {
       this.gmodel = gmodel;
       this.gnode = gnode;
       this.node = node;
       this.gview = gview;
    }

    @Override
    public void execute() {
       Set<Graphical> graphs =  gmodel.getAttachedObjects(gnode,Constants.getInportsString());
       for(Graphical g : graphs){
          if(g.getClass().isAssignableFrom(GInputPort.class)){
             GInputPort gin = (GInputPort)g;
             Location location = new FlexibleRelativeLocation(gin.getGraphLocation(), - gin.getWidth() - GInput.EXTRA_WIDTH, 0);
             InPort inport = (InPort)node.getPort(gin.getName());
             if(inport.getDefaultValue() != null){
                //determine the type of the store and add it
                 Store store = StoreFactory.createStore(inport.getValueClass().getSimpleName());
                 AddNodeCommand anc = new AddNodeCommand(gmodel, store.getClass());
                 anc.setLocation(location);
                 gview.notifyObservers(anc);
                 //make a connection
                 GNode gstore = anc.getGNode();
                 gstore.setValue(inport.getDefaultValue().toString());
                 ArrayList<Attachment> atts = gmodel.getAttachedAllNode(gstore);
                 GOutput gout = null;
                 Iterator<Attachment> it = atts.iterator();
                 while(it.hasNext() && gout == null){
                    Attachment current = it.next();
                     if(current.getClass().isAssignableFrom(GOutput.class)){
                        gout = (GOutput)current;
                    }
                 }
                 gview.notifyObservers(new AddConnectionCommand(gout,gin));
             }
         }
      }
   }
}
